import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { setToken, getToken, getPermissionToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

function comossion_pay(to, from, next, hasDomestic, path) {
  let status = hasDomestic.status;
  let oid = hasDomestic.oid ? hasDomestic.oid : 2;

  switch (status) {
    case "normal":
      path ? next(path) : next();
      break;
    case "pay":
      if (to.path != "/commission/pay") {
        next({
          path: "/commission/pay",
          query: {
            oid: oid
          }
        });
      } else {
        next();
      }
      break;
    case "notice":
      next();
      break;
  }
}

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  document.title = getPageTitle(to.meta.title);
  // determine whether the user has logged in
  const hasToken = getToken();
  const str = getPermissionToken();
  var hasPermissionToken = "";
  if (str) {
    hasPermissionToken = JSON.parse(str);
  }
  const hasDomestic = store.getters.domestic;

  if (hasToken) {
    if (to.path === "/login") {
      if (hasPermissionToken) {
        comossion_pay(to, from, next, hasPermissionToken, { path: "/" });
      } else {
        next();
      }
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.name;
      // 判断用户信息
      if (hasGetUserInfo) {
        if (hasPermissionToken && to.path != "/commission/pay") {
          comossion_pay(to, from, next, hasPermissionToken);
        } else {
          next();
        }
      } else {
        try {
          await store.dispatch("user/getInfo");
          if (hasPermissionToken) {
            comossion_pay(to, from, next, hasPermissionToken);
          } else {
            next();
          }
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (to.query.id) {
      let id = to.query.id;
      store.commit("user/SET_TOKEN", id);
      setToken(id);
      next({ path: "/" });
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  }
});

router.afterEach((to, from) => {
  // finish progress bar

  NProgress.done();
});
